package com.xz.patient.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.member.domain.MemberInfo;
import com.xz.member.domain.MemberLevel;
import com.xz.member.domain.MemberPatient;
import com.xz.member.domain.MemberRuleSetting;
import com.xz.member.mapper.MemberInfoMapper;
import com.xz.member.mapper.MemberLevelMapper;
import com.xz.member.mapper.MemberPatientMapper;
import com.xz.member.mapper.MemberRuleSettingMapper;
import com.xz.message.service.ISysTenantNotifyItemService;
import com.xz.message.vo.MemberMsgInfo;
import com.xz.patient.vo.PatientImportVo;
import com.xz.patient.vo.PatientInfoExportVo;
import com.xz.patient.vo.SendPatientVo;
import com.xz.product.domain.Product;
import com.xz.product.dto.ProductDto;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.purchase.dto.PurchaseImportVo;
import com.xz.supplier.domain.Supplier;
import com.xz.warehouse.domain.Warehouse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.patient.mapper.PatientInfoMapper;
import com.xz.patient.domain.PatientInfo;
import com.xz.patient.service.IPatientInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 患者信息Service业务层处理
 *
 * @author xz
 * @date 2024-01-30
 */
@Service
public class PatientInfoServiceImpl  extends ServiceImpl<PatientInfoMapper, PatientInfo> implements IPatientInfoService
{
    @Autowired
    private PatientInfoMapper patientInfoMapper;
    @Autowired
    private MemberPatientMapper memberPatientMapper;
    @Autowired
    private MemberInfoMapper memberInfoMapper;
    @Autowired
    private MemberLevelMapper memberLevelMapper;
    @Autowired
    private ISysTenantNotifyItemService sysTenantNotifyItemService;
    @Resource
    private MemberRuleSettingMapper memberRuleSettingMapper;
    /**
     * 查询患者信息
     *
     * @param id 患者信息主键
     * @return 患者信息
     */
    @Override
    public PatientInfo selectPatientInfoById(Long id)
    {
        return patientInfoMapper.selectPatientInfoById(id);
    }

    /**
     * 查询患者信息列表
     *
     * @param patientInfo 患者信息
     * @return 患者信息
     */
    @Override
    public List<PatientInfo> selectPatientInfoList(PatientInfo patientInfo)
    {
        return patientInfoMapper.queryList(patientInfo);
    }

    /**
     * 查询患者信息列表（导出）
     *
     * @param patientInfo 患者信息
     * @return 患者信息
     */
    @Override
    public List<PatientInfoExportVo> queryListForExport(PatientInfo patientInfo)
    {
      return patientInfoMapper.queryListForExport(patientInfo);
    }


    @Override
    public List<PatientInfo> findList(PatientInfo patientInfo)
    {
        List<PatientInfo> patientInfos = patientInfoMapper.queryList(patientInfo);
        return patientInfos;
    }


    /**
     * 新增患者信息
     *
     * @param patientInfo 患者信息
     * @return 结果
     */
    @Override
    public AjaxResult insertPatientInfo(PatientInfo patientInfo)
    {
//        String phoneNumber = patientInfo.getPhoneNumber();
//        PatientInfo byPhoneNumber = patientInfoMapper.findByPhoneNumber(phoneNumber);
//        if(Objects.nonNull(byPhoneNumber)){
//            return AjaxResult.error("手机号已注册！");
//        }
        PatientInfo patientInfo1 = patientInfoMapper.selectPatientInfo(patientInfo);
        if(Objects.nonNull(patientInfo1)){
            return AjaxResult.error("该患者信息已存在！");
        }
        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        patientInfo.setCreateBy(SecurityUtils.getUserId());
        patientInfo.setDeptId(deptId);
        patientInfo.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        int i = patientInfoMapper.insertPatientInfo(patientInfo);
        if(i>0){
            if(patientInfo.getIsRegisterMember().equals(1)){
                registerMember(patientInfo);
            }
        }
        return AjaxResult.success("操作成功！",patientInfo);
    }

    /**
     * 修改患者信息
     *
     * @param patientInfo 患者信息
     * @return 结果
     */
    @Override
    public AjaxResult updatePatientInfo(PatientInfo patientInfo)
    {
        patientInfo.setUpdateTime(DateUtils.getNowDate());
        patientInfoMapper.updatePatientInfo(patientInfo);
        return AjaxResult.success("操作成功！");
    }

    @Override
    public int  updateDept(PatientInfo patientInfo){
        PatientInfo patientInfoData = baseMapper.selectById(patientInfo.getId());
        patientInfoData.setDeptId(patientInfo.getDeptId());
        return baseMapper.updateById(patientInfoData);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int registerMember(PatientInfo patientInfo){
        PatientInfo patientInfoData = baseMapper.selectById(patientInfo.getId());
        MemberInfo memberInfoData = memberInfoMapper.memberInfoByCardNo(patientInfoData.getPhoneNumber());
        if(Objects.isNull(memberInfoData)){
            MemberInfo memberInfo = new MemberInfo();
            memberInfo.setPhoneNumber(patientInfoData.getPhoneNumber());
            memberInfo.setMemberCardNo(patientInfoData.getPhoneNumber());
            memberInfo.setBirthday(patientInfoData.getBirthday());
            memberInfo.setMemberName(patientInfoData.getPatientName());
            memberInfo.setSex(patientInfoData.getSex());
            memberInfo.setTenantId(patientInfoData.getTenantId());
            memberInfo.setDeptId(patientInfoData.getDeptId());
            memberInfo.setCreateBy(patientInfoData.getCreateBy());
            List<MemberLevel> list = memberLevelMapper.findList();
            if(!CollectionUtils.isEmpty(list)){
                memberInfo.setMemberLevelId(list.get(0).getId());
                memberInfo.setMemberLevel(list.get(0).getLevelNo());
            }
            memberInfoMapper.insert(memberInfo);
        }

        MemberPatient memberPatient = new MemberPatient();
        memberPatient.setRelationship(1);
        memberPatient.setPatientId(patientInfoData.getId());
        memberPatient.setMemberCardNo(patientInfoData.getPhoneNumber());

        // 说明已经是会员了 先查询一下
        List<MemberPatient> memberPatients = memberPatientMapper.selectMemberPatientList(memberPatient);
        if(!CollectionUtils.isEmpty(memberPatients)){
            throw new ServiceException("该患者已经是会员了!");
        }

        return memberPatientMapper.insert(memberPatient);
    }

    /**
     * 患者管理--营销短信·短信发送
     * @param sendPatientVo
     * @return
     */
    @Override
    public AjaxResult sendPatientSms(SendPatientVo sendPatientVo){
        Integer smsTemplateType = sendPatientVo.getSmsTemplateType();

        List<PatientInfo> byIdList = baseMapper.findByIdList(sendPatientVo.getIdList());
        List<MemberMsgInfo> infos = new ArrayList<>();
        for (PatientInfo patientInfo:byIdList) {
            MemberMsgInfo msgInfo = new MemberMsgInfo();
            BeanUtils.copyProperties(patientInfo,msgInfo);
            msgInfo.setStorePhone(patientInfo.getDeptName());
            msgInfo.setOperateStores(patientInfo.getDeptPhone());
            infos.add(msgInfo);
        }
        sysTenantNotifyItemService.sendListMemberInfoMsg(infos,smsTemplateType,SecurityUtils.getLoginUser().getUser());
        return AjaxResult.success("操作成功！");
    }

    @Override
    public AjaxResult importExcel(List<PatientImportVo> list){
        if(CollectionUtils.isEmpty(list)){
            return AjaxResult.error("导入数据不能为空");
        }
        //商品数据
        PatientInfo queryInfo = new PatientInfo();
        List<PatientInfo> patientInfos = baseMapper.selectPatientInfoList(queryInfo);
        Map<String,PatientInfo> map = new HashMap<>();
        for (PatientInfo patientInfo:patientInfos) {
            map.put(patientInfo.getPhoneNumber(),patientInfo);
        }

        List<MemberInfo> memberInfoList = memberInfoMapper.selectAllList();
        Map<String,MemberInfo> memberInfoMap = new HashMap<>();
        for (MemberInfo memberInfo:memberInfoList) {
            memberInfoMap.put(memberInfo.getMemberCardNo(),memberInfo);
        }

        List<PatientInfo> patientInfoList = new ArrayList<>();
        StringBuilder errorMsg=new StringBuilder();
        for(PatientImportVo importVo:list){
            if(Objects.nonNull(map.get(importVo.getPhoneNumber()))){
                errorMsg.append("<br/>【" + importVo.getPhoneNumber() + "】已存在! ");
                continue;
            }
            PatientInfo patientInfo = new PatientInfo();
            BeanUtils.copyProperties(importVo,patientInfo);
            int insert = baseMapper.insert(patientInfo);
            if(Objects.nonNull(importVo.getBindMemberCardNo())){
                if(Objects.nonNull(memberInfoMap.get(importVo.getBindMemberCardNo()))){
                    MemberPatient memberPatient = new MemberPatient();
                    memberPatient.setPatientId(patientInfo.getId());
                    memberPatient.setMemberCardNo(importVo.getBindMemberCardNo());
                    memberPatient.setRelationship(importVo.getBindRelationship());
                    memberPatient.setBindStatus(1);
                    memberPatientMapper.insert(memberPatient);
                }else {
                    errorMsg.append("<br/>【" + importVo.getPatientName() + "】绑定会员号+"+importVo.getBindMemberCardNo()+"失败,原因：会员号不存在! ");
                }
            }
            patientInfoList.add(patientInfo);
        }
        if(patientInfoList.size()==0){
            return AjaxResult.error("导入失败"+(StringUtils.isEmpty(errorMsg)?"":","+errorMsg.toString()));
        }
        boolean savedBatch = this.saveBatch(patientInfoList);
        if(!savedBatch){
            throw new ServiceException("导入失败");
        }
        return AjaxResult.success("导入成功"+(StringUtils.isEmpty(errorMsg)?"":",部分数导入失败<br/>"+errorMsg.toString()));

    }


    /**
     * 批量删除患者信息
     *
     * @param ids 需要删除的患者信息主键
     * @return 结果
     */
    @Override
    public int deletePatientInfoByIds(Long[] ids)
    {
        return patientInfoMapper.deletePatientInfoByIds(ids);
    }

    /**
     * 删除患者信息信息
     *
     * @param id 患者信息主键
     * @return 结果
     */
    @Override
    public int deletePatientInfoById(Long id)
    {
        return patientInfoMapper.deletePatientInfoById(id);
    }
}
